package com.jwater.gateway.common;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.gateway.filter.headers.HttpHeadersFilter;
import org.springframework.cloud.gateway.handler.AsyncPredicate;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.reactive.socket.client.WebSocketClient;
import org.springframework.web.reactive.socket.server.WebSocketService;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.pattern.PathPatternParser;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: jnner
 * @createDate: 2021/3/27
 * @version: 1.0
 */
@Configuration
public class CommonConfiguration {
    @Bean
    @ConditionalOnMissingBean
    public HttpMessageConverters messageConverters(ObjectProvider<HttpMessageConverter<?>> converters) {
        return new HttpMessageConverters(converters.orderedStream().collect(Collectors.toList()));
    }

    /**
     * 支持跨域接口访问
     *
     * @return
     */
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }

    /**
     * 通用断言工厂，拦截所有的url请求
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(CommonPredicateFactory.class)
    public CommonPredicateFactory commonPredicateFactory() {
        return new CommonPredicateFactory(CommonPredicateFactory.Config.class);
    }

    /**
     * 通用的全局网关过滤器，过滤所有的url请求
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(CommonGlobalFilter.class)
    public CommonGlobalFilter commonGlobalFilter() {
        return new CommonGlobalFilter();
    }

    /**
     * websocket处理器
     * @param webSocketClient
     * @param webSocketService
     * @param headersFiltersProvider
     * @return
     */
    @Bean
    public CommonWebsocketRoutingFilter commonWebsocketRoutingFilter(WebSocketClient webSocketClient,
                                                                 WebSocketService webSocketService,
                                                                 ObjectProvider<List<HttpHeadersFilter>> headersFiltersProvider) {
        return new CommonWebsocketRoutingFilter(webSocketClient, webSocketService, headersFiltersProvider);
    }

    /**
     * 添加自定义的路由处理器，拦截所有的URL请求
     *
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator addRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes().route("common", predicateSpec -> {
            AsyncPredicate<ServerWebExchange> commonPredicate = commonPredicateFactory()
                    .applyAsync(new CommonPredicateFactory.Config());
            return predicateSpec.asyncPredicate(commonPredicate).filters(filterSpec -> {
                return filterSpec;
            }).uri("dynamic://address");
        }).build();
    }
}
